<!--
 * @Author: error: git config user.name && git config user.email & please set dead value or install git
 * @Date: 2023-01-04 20:44:55
 * @LastEditors: 朱安武 549410045@qq.com
 * @LastEditTime: 2023-01-06 15:15:50
 * @FilePath: \vue-test\elementUi\src\components\BannerForm.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
    <div>
      <el-form
        label-width="100px"
        :model="formData.formData"
        :rules="rules"
        ref="bannerForm"
      >
        <el-form-item label="图片" prop="img">
          <el-upload
            ref="upload"
            :limit="1"
            :auto-upload="false"
            list-type="picture"
            :on-exceed="onExceed"
            :on-change="onChangeImg"
          >
            <template #trigger>
              <el-button type="primary">选择文件</el-button>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="图片文案" prop="alt">
          <el-input v-model="formData.formData.alt" />
        </el-form-item>
        <el-form-item label="跳转链接" prop="link">
          <el-input v-model="formData.formData.link" />
        </el-form-item>
        <el-form-item>
          <el-button @click="handleSubmit">提交</el-button>
        </el-form-item>
      </el-form>
    </div>
</template>
<script setup>
import { genFileId } from 'element-plus'

import { addBanner } from '../services/index'

import{ reactive,getCurrentInstance }from 'vue'

//定义事件
const props = defineProps(['dialogVisible'])
const emit = defineEmits(['on-add-succuss'])

   
//定义数据
const formData = reactive({
  formData:{
    img:'',
    alt: '',
    link: ''
  }
})

//定义规则
const rules = reactive({
        img: [
          { required: true, trigger: 'blur', message: '请选择图片' }
        ],
        alt: [
          { required: true, trigger: 'blur', message: '请填写文案' }
        ],
        link: [
          { required: true, trigger: 'blur', message: '请填写地址' }
        ],
})

//提交
const th = getCurrentInstance()

const handleSubmit = ()=>{
  th.refs.bannerForm.validate((volid)=>{
    //成功
    if(volid){
      addBanner(formData.formData).then((result)=>{
        //调用事件
        emit('on-add-succuss')
        //清空表单
        th.refs.bannerForm.resetFields()
        th.refs.upload.clearFiles()
      })
    }
  })
}

//验证上传
const onExceed = files=>{
  th.refs.upload.clearFiles()

  const file = files[0]
  file.uid = genFileId()

  th.refs.upload.handleStart(file)
}

//转换图片base 64 类型
const onChangeImg = file=>{
  const fileReader = new FileReader()
  fileReader.onload = ()=>{
    formData.formData.img = fileReader.result
  }
  fileReader.readAsDataURL(file.raw)
}
</script>